
#include "s3c-jpeg.h"
#include "jpg_opr.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <fcntl.h>
#include <unistd.h>

#include <linux/videodev2.h>

#include <sys/ioctl.h>
#include <sys/mman.h>

struct jpg_args mArgs;

int main(int argc, char **argv)
{
	int img_size = 800 * 480 * 4;
	int jfd = open("/dev/s3c-jpg", O_RDWR);

	enum jpg_return_status ret = JPG_FAIL;
	
	char bbuf[768000] = {0};

	if(0 > jfd)
	{
		perror("open");
		return -1;
	}
	
	memset(&mArgs, 0, sizeof(mArgs));
	
	mArgs.mapped_addr = mmap(0, img_size, PROT_READ | PROT_WRITE, MAP_SHARED, jfd, 0);
	
	if(MAP_FAILED == mArgs.mapped_addr)
	{
		perror("mmap");
		return -1;
	}

	printf("%p\n", mArgs.mapped_addr);
	
	mArgs.enc_param = (struct jpg_enc_proc_param *)malloc(sizeof(struct jpg_enc_proc_param));
	
	mArgs.enc_param->sample_mode = JPG_422;
	mArgs.enc_param->enc_type = JPG_MAIN;
	mArgs.enc_param->in_format = JPG_MODESEL_RGB;
	mArgs.enc_param->quality = JPG_QUALITY_LEVEL_1;
	mArgs.enc_param->width = 800;
	mArgs.enc_param->height = 480;
	//enc_param.data_size = 
	//enc_param.file_size = 
	
	mArgs.in_buf = (char *)ioctl(jfd, IOCTL_JPG_GET_FRMBUF, mArgs.mapped_addr);
	
	if(MAP_FAILED == mArgs.in_buf)
	{
		perror("mmap");
		return -1;
	}

	printf("%p\n", mArgs.in_buf);
	
	int bfd = open("/tmp/test.bmp", O_RDWR);

	if(0 <= bfd)
	{
		printf("%u\n", read(bfd, bbuf, sizeof(bbuf)));
		close(bfd);
		printf("read success\n");
		
		memcpy(mArgs.in_buf, bbuf, sizeof(bbuf));
		
		ret = (enum jpg_return_status)ioctl(jfd, IOCTL_JPG_ENCODE, &mArgs);
		
		if(ret != JPG_SUCCESS)
		{
			printf("++++++++IOCTL_JPG_ENCODE failed\n");
			return -1;
		}
		
		mArgs.out_buf = (char *)ioctl(jfd, IOCTL_JPG_GET_STRBUF, mArgs.mapped_addr);
		
		bfd = open("/tmp/test.jpg", O_RDWR | O_CREAT, 0666);
		if(0 <= bfd)
		{
			printf("%u\n", write(bfd, mArgs.out_buf, mArgs.enc_param->file_size));
			close(bfd);
			printf("write success\n");
		}
		else
		{
			perror("???");
		}
	}

	printf("success\n");

	munmap(mArgs.mapped_addr, img_size);
	close(jfd);

	return 0;
}